// src/components/ChatInterface.tsx
import { useState } from 'react';
import axios from 'axios';

const SILICON_API_URL = 'https://api.siliconflow.cn/v1/chat'; // 官方API地址
const API_KEY = 'sk-ljozyzqdpkxfuenqtprtsmpqxzsloywnpasyaokinepjmrjs'; // 替换为实际API密钥

interface Message {
    role: 'user' | 'assistant';
    content: string;
}

const ChatInterface = () => {
    const [messages, setMessages] = useState<Message[]>([]);
    const [inputText, setInputText] = useState('');
    const [isLoading, setIsLoading] = useState(false);

    // 发送消息到硅基智能API
    const sendMessage = async () => {
        if (!inputText.trim() || isLoading) return;

        try {
            setIsLoading(true);
            const newMessages = [...messages, { role: 'user', content: inputText }];

            // 调用API
            const response = await axios.post(
                SILICON_API_URL,
                {
                    messages: newMessages,
                    model: 'DeepSeek-R1 (Pro)', // 根据文档选择模型
                    temperature: 0.6,
                },
                {
                    headers: {
                        'Authorization': `Bearer ${API_KEY}`,
                        'Content-Type': 'application/json',
                    },
                }
            );

            // 解析响应
            const aiResponse = response.data.choices.message.content;
            setMessages([...newMessages, { role: 'assistant', content: aiResponse }]);
        } catch (error) {
            console.error('API请求失败:', error);
            alert('对话服务暂时不可用，请稍后重试');
        } finally {
            setIsLoading(false);
            setInputText('');
        }
    };

    return (
        <div className="chat-container">
            <div className="message-area">
                {messages.map((msg, index) => (
                    <div key={index} className={`message ${msg.role}`}>
                        {msg.content}
                    </div>
                ))}
                {isLoading && <div className="loading">硅基AI正在思考...</div>}
            </div>

            <div className="input-area">
                <input
                    type="text"
                    value={inputText}
                    onChange={(e) => setInputText(e.target.value)}
                    onKeyPress={(e) => e.key === 'Enter' && sendMessage()}
                    placeholder="输入你的问题"
                    disabled={isLoading}
                />
                <button onClick={sendMessage} disabled={isLoading}>
                    {isLoading ? '发送中...' : '发送'}
                </button>
            </div>
        </div>
    );
};

export default ChatInterface;